import { Module, Global } from '@nestjs/common';
import * as mysql from 'mysql2/promise';
import { DATA_BASE } from '@/common/constant';
import { DatabaseService } from './database.service';

@Global()
@Module({
  providers: [
    {
      provide: 'MYSQL_CONNECTION',
      useFactory: async () => {
        const pool = mysql.createPool({
          ...DATA_BASE,
          waitForConnections: true,
          connectionLimit: 10,
          queueLimit: 0,
        });

        try {
          const connection = await pool.getConnection();
          await connection.ping();
          // eslint-disable-next-line no-console
          console.log('✅ MySQL 数据库连接成功');
          connection.release();
        } catch (error) {
          console.error('❌ MySQL 数据库连接失败:', (error as Error).message);
        }

        return pool;
      },
    },
    DatabaseService, // 👈 注册 DatabaseService
  ],
  exports: ['MYSQL_CONNECTION', DatabaseService], // 👈 导出它
})
export class DatabaseModule {}
